/*******************************************************************************
 * Copyright (c) Jerges A. Bello G. 2014. Reservado todos los derechos.
 ******************************************************************************/
package com.jabex.persistence.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jabex.persistence.model.Identity;

/**
 * Created with IntelliJ IDEA.
 * User: Jerges Bello
 * Date: 5/11/13
 * Time: 22:47
 * To change this template use File | Settings | File Templates.
 */
@Component
public class SpringHibernateDAO<B extends Identity> implements IAccessDAO<B> {


    private static SessionFactory sessionFactory;

    protected Class<B>				modelClass;


    @Autowired
    public SpringHibernateDAO(SessionFactory sessionFactory) {
	    SpringHibernateDAO.sessionFactory = sessionFactory;
    }

	public SpringHibernateDAO(Class<B> modelClass) {
		this.modelClass = modelClass;
    }


	public String persist(B entity) throws HibernateException {
		getCurrentSession().persist(entity);
		/*getCurrentSession().getTransaction().commit();*/
		return String.valueOf(entity.getId());
	}

    private Session getCurrentSession()  {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession();
	}


	public boolean update(B entity)throws HibernateException{
		boolean execute;
		getCurrentSession().saveOrUpdate(entity);
		/*getCurrentSession().getTransaction().commit();*/
		execute = true;
		return execute;
	}


	public boolean delete(B entity) throws HibernateException{
	    boolean execute;
    	getCurrentSession().delete(entity);
		/*getCurrentSession().getTransaction().commit();*/
	    execute = true;
	    return execute;
    }


	public B getObjectById(String id) throws HibernateException{
    	return (B) getCurrentSession().get(modelClass,  Long.valueOf(id));
    }


	public List<B> getObjectByParameters(B bean) throws HibernateException{

        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public List<B> getAllRows(B entity) throws HibernateException{
        return getCurrentSession().createCriteria(modelClass).list();
    }
    
}
